import React, { useEffect, useState } from "react";
import CryptoJS from "crypto-js";
import RecorderManager from "./js/RecorderManager";
// 系统配置
const config = {
  // 请求地址
  hostUrl: "wss://rtasr.xfyun.cn/v1/ws",
  appid: "ee62ae20",
  apiKey: "a90b5ce28ebf3375a58dd00602a2a3e3",
};

let iatWS;
let resultText = "";
let resultTextTemp = "";
let countdownInterval = null;
let btnStatus = "UNDEFINED"; // "UNDEFINED" "CONNECTING" "OPEN" "CLOSING" "CLOSED"
let recorder;

export default function notFound() {
  const [btnTxt, setBtnTxt] = useState("点击开始");
  const [resultVal, setResultVal] = useState("");

  useEffect(() => {
    recorder = new RecorderManager("");
    recorder.onStart = () => {
      changeBtnStatus("OPEN");
    };
    recorder.onFrameRecorded = (val) => {
      let { isLastFrame, frameBuffer } = val;
      if (iatWS.readyState === iatWS.OPEN) {
        iatWS.send(new Int8Array(frameBuffer));
        if (isLastFrame) {
          iatWS.send('{"end": true}');
          changeBtnStatus("CLOSING");
        }
      }
    };
    recorder.onStop = () => {
      clearInterval(countdownInterval);
    };
    console.log("RecorderManager", recorder);
    // connectWebSocket();
  }, []);
  //   签名
  const getSigna = (ts) => {
    let md5 = CryptoJS.MD5(config.appid + ts).toString();
    let sha1 = CryptoJS.HmacSHA1(md5, config.apiKey);
    let base64 = CryptoJS.enc.Base64.stringify(sha1);
    return encodeURIComponent(base64);
  };
  const changeBtnStatus = (status) => {
    btnStatus = status;
    if (status === "CONNECTING") {
      setBtnTxt("建立连接中");
      setResultVal("");
      resultText = "";
      resultTextTemp = "";
    } else if (status === "OPEN") {
      setBtnTxt("录音中...");
    } else if (status === "CLOSING") {
      setBtnTxt("关闭连接中");
    } else if (status === "CLOSED") {
      setBtnTxt("开始录音");
    }
  };
  const renderResult = (resultData) => {
    let jsonData = JSON.parse(resultData);
    console.log("收到消息：", jsonData);

    if (jsonData.action == "started") {
      // 握手成功
      console.log("握手成功");
    } else if (jsonData.action == "result") {
      const data = JSON.parse(jsonData.data);
      console.log(data);
      // 转写结果
      let resultTextTemp = "";
      data.cn.st.rt.forEach((j) => {
        j.ws.forEach((k) => {
          k.cw.forEach((l) => {
            resultTextTemp += l.w;
          });
        });
      });
      if (data.cn.st.type == 0) {
        // 【最终】识别结果：
        resultText += resultTextTemp;
        resultTextTemp = "";
      }

      setResultVal(resultText + resultTextTemp);
    } else if (jsonData.action == "error") {
      // 连接发生错误
      console.log("出错了:", jsonData);
    }
  };

  const connectWebSocket = () => {
    let ts = parseInt(new Date().getTime() / 1000);
    let websocketUrl =
      config.hostUrl +
      "?appid=" +
      config.appid +
      "&ts=" +
      ts +
      "&signa=" +
      getSigna(ts);
    if ("WebSocket" in window) {
      iatWS = new WebSocket(websocketUrl);
    } else if ("MozWebSocket" in window) {
      iatWS = new MozWebSocket(websocketUrl);
    } else {
      alert("浏览器不支持WebSocket");
      return;
    }
    changeBtnStatus("CONNECTING");
    iatWS.onopen = (e) => {
      // 开始录音
      recorder.start({
        sampleRate: 16000,
        frameSize: 1280,
      });
    };
    iatWS.onmessage = (e) => {
      renderResult(e.data);
    };
    iatWS.onerror = (e) => {
      console.error(e);
      recorder.stop();
      changeBtnStatus("CLOSED");
    };
    iatWS.onclose = (e) => {
      recorder.stop();
      changeBtnStatus("CLOSED");
    };
  };

  const btnFun = () => {
    if (btnStatus === "UNDEFINED" || btnStatus === "CLOSED") {
      connectWebSocket();
    } else if (btnStatus === "CONNECTING" || btnStatus === "OPEN") {
      // 结束录音
      recorder.stop();
    }
  };
  return (
    <>
      <div>403 页面测试中。。。</div>
      <button onClick={btnFun}>按钮：{btnTxt}</button>
      <div>结果：{resultVal}</div>
    </>
  );
}
